<template>
  <div class="note-editor">
    <div v-if="section.id == NoteSection.Phonetics">
      <div class="note-title">编辑注音</div>
      <pinyin-input v-model="content"></pinyin-input>
    </div>
    <div v-else>
      <div class="note-title">编辑笔记</div>
      <mavon-editor v-model="content"></mavon-editor>
    </div>
    <el-button type="primary" @click="saveNote">保存</el-button>
    <el-button @click="$emit('close')">取消</el-button>
  </div>
</template>

<script>
import {MatFormat, MatKind, NoteSection} from "@js/constants.js";
import PinyinInput from "./PinyinInput.vue";
export default {
  components: {
    PinyinInput
  },
  props: ["context", "section", "value"],
  data() {
    return {
      NoteSection: NoteSection,
      content: ""
    }
  },
  methods: {
    onInput() {
      //this.note.content = ev;
      this.$emit('input', this.note)
    },
    saveNote() {
      console.log("start saving note");
      let note = {};
      var url = "";
      if ("id" in this.context && this.context.id) {
        // 修改
        url = "/api/v1/notes/modify";
        note.content = this.content;
      } else {
        // 新建
        url = "/api/v1/notes/add";
        let ctx = this.context;
        if (!ctx.mat || !ctx.mat.id) {
          // 如果当前素材还没有建立数据库选项（例如代码），就需要先调用素材创建接口
          this.authPost("/api/v1/mats/addpath?path="+ctx.mat.title).then(res => {
            let mat = res.data;
            ctx.mat = mat;
            this.saveNote();
          });
          return;
        }
        let format = note.section == NoteSection.Phonetics ? MatFormat.Phonetics: MatFormat.Markdown;
        note.kind = MatKind.Note;
        note.line = ctx.line;
        note.format = format;
        note.content = this.content;
        let s = ctx.s || {
          mid: ctx.mat.id,
          line: 0,
          pos: 0
        };
        note.section = this.section.id;
        note.scope = ctx.scope;
        note.s = s;
        note.e = ctx.e || s;
      }

      console.log("saving note:", JSON.stringify(note));
      return this.authPost(url, note)
        .then((res) => {
          let noteid = res.data.id;
          note.id = noteid;
          this.$emit("close");
          return note;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  }
};
</script>

<style lang="stylus">
.note-editor
  padding 20px
  border 1px dashed #eee
  border-radius 4px
  background-color #fafafa

  &>div
    margin-bottom 20px

  .note-title
    font-weight bold
    margin-bottom 20px
</style>